package cn.itsource.order.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.order.domain.Product;
import cn.itsource.order.domain.ProductDetail;
import cn.itsource.order.mapper.ProductDetailMapper;
import cn.itsource.order.mapper.ProductMapper;
import cn.itsource.order.query.ProductQuery;
import cn.itsource.order.service.IProductDetailService;
import cn.itsource.order.service.IProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import tk.mybatis.mapper.entity.Example;

import javax.swing.text.StyledEditorKit;

@Service
public class ProductServiceImpl
        extends BaseServiceImpl<Product, ProductQuery>
        implements IProductService {

    @Autowired(required = false)
    private ProductDetailMapper productDetailMapper;

    @Autowired(required = false)
    private ProductMapper productMapper;

    @Override
    public PageList<Product> queryPage(ProductQuery query) {
        PageHelper.startPage(query.getPageIndex(), query.getPageSize());
        Example example = new Example(Product.class);
        if (StringUtils.isNotBlank(query.getKeyword())) {
            example.and().andLike("name", "%" + query.getKeyword() + "%");
        }
        List<Product> products = mapper.selectByExample(example);
        PageInfo<Product> info = new PageInfo<>(products);

        return new PageList<>(info.getTotal(), info.getList());
    }

    @Override
    public boolean onoff(Long[] id, Long state) {
        for (Long i : id) {
            productMapper.onOff(i,state);
        }
        return true;
    }

    @Override
    public boolean save(Product model) {
        boolean result;
        if (find(model.getId()) == null) {
            mapper.insertSelective(model);
            Long id = model.getId();
            ProductDetail detail = new ProductDetail();
            detail.setIntro(model.getIntro());
            detail.setOrderNotice(model.getOrderNotice());
            detail.setProductId(id);

            return productDetailMapper.insertSelective(detail) > 0;
        } else {
            Long id = model.getId();
            ProductDetail detail = new ProductDetail();
            detail.setIntro(model.getIntro());
            detail.setOrderNotice(model.getOrderNotice());
            detail.setProductId(id);
            mapper.updateByPrimaryKeySelective(model);
            result = productDetailMapper.updateByPrimaryKeySelective(detail) > 0;
        }
        return result;
    }
}
